package com.example.sqlexecutor.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Controller
public class SqlExecutorController {
    
    @Autowired
    private JdbcTemplate jdbcTemplate;
    
    @GetMapping({"/", "/sql-executor"})
    public String sqlExecutorPage() {
        return "sql-executor";
    }
    
    @PostMapping("/execute-sql")
    @ResponseBody
    public Map<String, Object> executeSql(@RequestParam String sql) {
        Map<String, Object> result = new HashMap<>();
        try {
            // 简单的SQL注入防护，仅允许SELECT语句
            if (!sql.trim().toLowerCase().startsWith("select")) {
                throw new RuntimeException("只允许执行SELECT语句");
            }
            
            List<Map<String, Object>> data = jdbcTemplate.queryForList(sql);
            if (!data.isEmpty()) {
                Set<String> columns = data.get(0).keySet();
                result.put("columns", columns);
                result.put("data", data);
            }
            result.put("success", true);
        } catch (Exception e) {
            result.put("success", false);
            result.put("error", e.getMessage());
        }
        return result;
    }
} 